package com.goodcol.plugin.actions;

import com.goodcol.plugin.service.CodeGenerateService;
import com.goodcol.plugin.tool.CacheDataUtils;
import com.goodcol.plugin.tool.TypeMapperUtils;
import com.goodcol.plugin.ui.MainGenerate;
import com.intellij.database.psi.DbTable;
import com.intellij.openapi.actionSystem.ActionUpdateThread;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.PlatformDataKeys;
import com.intellij.openapi.project.Project;
import com.intellij.psi.PsiElement;
import org.jetbrains.annotations.NotNull;

import java.util.Arrays;

/**
 * 代码生成菜单
 *
 * @author QuickCode
 * @version 1.0.0
 */
public class GenerateMainAction extends AnAction {

    /**
     * 处理方法
     *
     * @param event 事件对象
     */
    @Override
    public void actionPerformed(@NotNull AnActionEvent event) {
        Project project = event.getProject();
        if (project == null) {
            return;
        }
        // 处理选中的表 和 校验类型映射
        if (!CodeGenerateService.getInstance(project).cacheSelectedTables(event)
                || !TypeMapperUtils.processTypeValidator(project, CacheDataUtils.getInstance().getDbTableList())) {
            return;
        }
        //开始处理
        new MainGenerate(event.getProject()).show();
    }

    @Override
    public void update(@NotNull AnActionEvent e) {
        super.update(e);
        //获取选中的PSI元素
        boolean selectTableFlag = false;
        PsiElement[] psiElements = e.getData(PlatformDataKeys.PSI_ELEMENT_ARRAY);
        if (psiElements != null) {
            selectTableFlag = Arrays.stream(psiElements).anyMatch(item -> item instanceof DbTable);
        }
        e.getPresentation().setEnabled(selectTableFlag);
    }

    @Override
    public @NotNull ActionUpdateThread getActionUpdateThread() {
        return ActionUpdateThread.BGT;
    }
}
